package com.mzba.place.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockFragment;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.NotificationListAdapter;
import com.mzba.place.entity.NotificationEntity;
import com.mzba.place.entity.NotificationInfoGson;
import com.mzba.place.ui.MainActivity;
import com.mzba.place.ui.ReportDetailActivity;
import com.mzba.place.ui.widget.CustomListView;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageLoader;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 我的通知
 * @author 06peng
 *
 */
public class MyNotificationFragment extends SherlockFragment implements Callback, BasicUIEvent  {
	
	private MainActivity mainActivity;
	private CustomListView listView;
	private List<NotificationEntity> notifications;
	private NotificationEntity entry;
	private NotificationListAdapter notificationListAdapter;
	private ImageLoader mImageLoader;
//	private double localLat;
//	private double localLon;
	public PlaceApplication app;
	public LocationClient mLocClient;
	private Handler handler;
	
	private final int init_notifications = 1;
	private final int notifications_read = 2;
	private final int notifications_all_read = 3;
	int currentPosition;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getSherlockActivity();
		handler = new Handler(this);
		app = (PlaceApplication) mainActivity.getApplication();
//        if (app.mBMapManager == null) {
//            app.mBMapManager = new BMapManager(mainActivity);
//            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
//        }
//        app.getMyListener().setHander(handler);
//        mLocClient = app.mLocationClient;
		mImageLoader = ImageLoader.getInstance(mainActivity);
//		menuMyPosition();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_report_list, null);
		listView = (CustomListView) view.findViewById(R.id.list_report);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//				Intent intent = new Intent();
//				intent.setClass(mainActivity, ReportDetailActivity.class);
//				intent.putExtra("report_detail", notificationListAdapter.getNotificationList().get(arg2-1).getReport());
//				startActivity(intent);
				if (notificationListAdapter!=null) {
					entry = notificationListAdapter.getNotificationList().get(arg2-1);
					currentPosition = arg2-1;
					UICore.eventTask(MyNotificationFragment.this, mainActivity, notifications_read, null, true);
				}
				
			}
		});
		
		
		return view;
	}
	
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
		UICore.eventTask(this, mainActivity, init_notifications, null, true);
	}


	OnScrollListener onScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				mImageLoader.lock();
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				mImageLoader.unlock();
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				mImageLoader.lock();
				break;
			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			
		}
	};
	
	/**
	 * locate to my position
	 */
	public void menuMyPosition() {
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			
		option.setCoorType("bd09ll");		
		option.setAddrType("all");	
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);      
		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			String response = null;
			switch (mes) {
			case init_notifications:
				String url = UrlConfig.notification_unread;
				url += "?auth_token=" + AppContext.getInstance().getAuthToken();
				Log.d("debug", "url---===>"+url);
				response = HttpUtils.doGet(url);
				Log.d("debug", "response---通知栏-===>"+response);
//				response ="{\"notifications\":[{\"id\":8,\"is_read\":false,\"created_at\":\"2013-08-13 06:58:35\",\"notify_type\":\"mine_comment\",\"comment\":\"谢谢你的分享\",\"user\":{\"id\":100003,\"username\":\"fsdfsdf\",\"avatar_url\":\"http://192.168.1.120:3000/assets/avatar.png\"},\"report\":{\"id\":2,\"text\":\"前两天在这下车的时候手机被偷了\",\"type_id\":1,\"thumbnail_pic\":null,\"bmiddle_pic\":null,\"created_at\":\"2013-04-22T11:03:46+08:00\"}}]}";
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					NotificationInfoGson reportGson = gson.fromJson(response, NotificationInfoGson.class);
					if (reportGson != null) {
						notifications = reportGson.getNotifications();	
					}
				}
				handler.sendEmptyMessage(init_notifications);
				break;
			case notifications_read:
				String one_read_url = UrlConfig.notificationa_read_one+entry.getId() + "";
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
				response = HttpUtils.put(mainActivity, one_read_url, paramsMap);
				Log.d("debug", "response---===>"+response);
				if (response!=null) {
					if (getRc(response) == 0) {
						
					}
				}
				handler.sendEmptyMessage(notifications_read);
				
				break;
			case notifications_all_read:
//				String all_read = UrlConfig.notificationa_all_read+ "";
//				HashMap<String, String> paramsMap1 = new HashMap<String, String>();
//				paramsMap1.put("auth_token", AppContext.getInstance().getAuthToken());
				StringBuilder builder = new StringBuilder();
				builder.append(UrlConfig.notificationa_all_read+ "");
				builder.append("?auth_token=");
				builder.append(AppContext.getInstance().getAuthToken());
				response = HttpUtils.doGet(builder.toString());

				Log.d("debug", "response---===>"+response);
				if (response!=null) {
					if (getRc(response) == 0) {
						handler.sendEmptyMessage(notifications_all_read);
					}
				}
				
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_notifications:
			if (notifications != null && !notifications.isEmpty()) {
				notificationListAdapter = new NotificationListAdapter(mainActivity, notifications, mImageLoader);
				listView.setAdapter(notificationListAdapter);
				
			} else {
				List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("value", "暂无数据");
				data.add(map);
				SimpleAdapter adapter = new SimpleAdapter(mainActivity, data, R.layout.empty_listitem, 
						new String[] {"value"}, new int[] {R.id.value});
				listView.setAdapter(adapter);
			}
			break;
//		case AppContext.LOCATE:
//			localLat = app.latitude;
//			localLon = app.longitude;
//			break;
		case notifications_read:
			try {
//				notificationListAdapter.getNotificationList().get(currentPosition).setIs_read(true);
//				notificationListAdapter.notifyDataSetChanged();
				Intent intent = new Intent();
				intent.setClass(mainActivity, ReportDetailActivity.class);
				intent.putExtra("report_detail", entry.getReport());
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case notifications_all_read:
			try {
				notificationListAdapter.getNotificationList().get(currentPosition).setIs_read(true);
				int size = notifications.size();
				boolean isRead;
				for (int i = 0; i < size; i++) {
					isRead = notifications.get(i).isIs_read();
					if (!isRead) {
						notifications.get(i).setIs_read(true);
					}
				}
				notificationListAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		return false;
	}

	private int getRc(String json) {
		JSONObject jsonObject;
		int rc = 1;
		try {
			jsonObject = new JSONObject(json);
			rc = jsonObject.getInt("rc");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return rc;
	}
	
	/**
	 * 设置所以的通知为已读
	 */
	public void setAllNotificationRead(){
		UICore.eventTask(MyNotificationFragment.this, mainActivity, notifications_all_read, null, true);
	}
}
